package com.ly.hotel.spainterface.pp.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jxd.bean.MachineBean;
import com.ly.hotel.spainterface.jxd.utils.MachineUtils;
import com.ly.hotel.spainterface.pp.adapter.PpItemAdapter;
import com.ly.hotel.spainterface.pp.adapter.PpXFListAdapter;
import com.ly.hotel.spainterface.pp.bean.PpXFPluginBean;
import com.ly.hotel.spainterface.pp.bean.PreItemBean;
import com.ly.hotel.spainterface.pp.bean.PreItemReturnBean;
import com.ly.hotel.spainterface.pp.bean.PreXFDataBean;
import com.ly.hotel.spainterface.pp.bean.PreXFDataReturnBean;
import com.ly.hotel.spainterface.pp.utils.CommonHttpUtils;
import com.ly.hotel.spainterface.pp.utils.GsonUtils;
import com.ly.hotel.spainterface.pp.utils.PPXmlParseUtils;
import com.ly.hotel.spainterface.pp.view.CommentCustomToast;
import com.ly.hotel.spainterface.pp.view.PpXFDetailsDialog;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.view.TitleLayout;
import com.ly.hotel.view.common.BaseActivity;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mo on 2018/6/6.
 */

public class PPXFActivity extends BaseActivity {

    private final String TAG = "PPXFActivity";
    private ListView xfCategoryListview;
    private RelativeLayout categoryDownMore;
    private MachineBean machineBean;
    private PpXFPluginBean ppXFPluginBean;
    private final int CONSUME_CATEGORY = 0;
    private final int CONSUME_DATA = 1;
    private Gson gson = new Gson();
    private List<PreItemBean> itemBeans;
    private boolean isFirstGetConsume = true;// 是否是第一次请求消费数据
    private List<PreXFDataBean> xfDataBeans;
    private TextView consumeCategoryName;
    private TextView consumeItemNum;
    private GridView consumeItemGridview;
    private TextView noConsumeItem;
    private RelativeLayout consumeItemDownMore;
    private List<PreXFDataBean> tempPreXFDataBean = new ArrayList<>();
    private int itemId;
    private PpXFListAdapter xfListAdapter;
    private String itemName;
    private MyHandler handler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pp_xf_activity);
        initView();
        getPluginConfig();
        getMachineInfo();
        getConsumeItem();
    }

    private void initView() {
        TitleLayout titleLayout = findViewById(R.id.title_layout);
        TextView titleName = titleLayout.findViewById(R.id.activity_name);
        titleName.setTextColor(ContextCompat.getColor(this, R.color.mainWhite));
        titleName.setText(getResources().getString(R.string.naviXiaofeiName));

        xfCategoryListview = findViewById(R.id.xf_category_listview);
        categoryDownMore = findViewById(R.id.category_down_more);

        consumeCategoryName = findViewById(R.id.consume_category_name);
        consumeItemNum = findViewById(R.id.consume_item_num);

        consumeItemGridview = findViewById(R.id.consume_item_gridview);
        noConsumeItem = findViewById(R.id.no_consume_item);
        consumeItemDownMore = findViewById(R.id.consume_item_down_more);
    }

    // 获取插件配置
    private void getPluginConfig() {
        ppXFPluginBean = PPXmlParseUtils.getInstance().parsePpXFPlugin(MyApplication.pluginCfg, MyApplication.interfaceVersion);
    }

    // 获取本机IP、Port、mac地址、电视类别、位置号
    private void getMachineInfo() {
        machineBean = MachineUtils.getHostAndTvInfo();
    }

    // 请求消费项目类别
    private void getConsumeItem() {
        if (ppXFPluginBean != null) {
            if (!TextUtils.isEmpty(ppXFPluginBean.getIp()) && !TextUtils.isEmpty(ppXFPluginBean.getPort())) {
                ProcessWaitingUtil.showProcessDialog(this, getResources().getString(R.string.loading_tips), 10000);
                String URL = "http://" + ppXFPluginBean.getIp() + ":" + ppXFPluginBean.getPort() + "/api/consume-category.json";
                String request = null;
                CommonHttpUtils.getResource(URL, request, handler, CONSUME_CATEGORY);
            } else {
                CommentCustomToast.makeText(this, "ip或port插件配置为空！", Toast.LENGTH_SHORT, false).show();
            }
        } else {
            CommentCustomToast.makeText(this, "插件配置出错！", Toast.LENGTH_SHORT, false).show();
        }
    }

    // 请求技师数据
    private void getConsumeData() {
        ProcessWaitingUtil.showProcessDialog(this, getResources().getString(R.string.loading_tips), 10000);
        String URL = "http://" + ppXFPluginBean.getIp() + ":" + ppXFPluginBean.getPort() + "/api/consume.json";
        String request = null;
        CommonHttpUtils.getResource(URL, request, handler, CONSUME_DATA);
    }

    private void setConsumeCategoryAdapter() {
        if (itemBeans.size() == 0) {
            CommentCustomToast.makeText(this, "后台没配置消费类型！", Toast.LENGTH_SHORT, false).show();
        } else {
            final PpItemAdapter itemAdapter = new PpItemAdapter(this, itemBeans);
            xfCategoryListview.setAdapter(itemAdapter);
            xfCategoryListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    itemAdapter.setDefaultPosition(position);
                    PreItemBean itemBean = itemBeans.get(position);
                    // 项目名称
                    itemName = itemBean.getName();
                    Log.i(TAG, "itemName=" + itemName);
                    // 项目ID
                    itemId = itemBean.getId();
                    if (isFirstGetConsume) {
                        isFirstGetConsume = false;
                        getConsumeData();
                    } else {
                        setConsumeList();
                    }
                }
            });
            xfCategoryListview.performItemClick(xfCategoryListview.getChildAt(0), 0,
                    xfCategoryListview.getItemIdAtPosition(0));

            xfCategoryListview.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    if ((firstVisibleItem == 0 && visibleItemCount == totalItemCount) || firstVisibleItem > 0 && firstVisibleItem + visibleItemCount == totalItemCount) {
                        categoryDownMore.setVisibility(View.GONE);
                    } else {
                        categoryDownMore.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    // 设置消费列表
    private void setConsumeList() {
        if (xfDataBeans == null) {
            CommentCustomToast.makeText(PPXFActivity.this, "消费列表为空，请在后台添加！",
                    Toast.LENGTH_SHORT, false).show();
            if (xfListAdapter != null) {
                xfListAdapter.notifyDataSetChanged();
            }
        } else {
            // 筛选不同消费类别的消费项目数据
            tempPreXFDataBean.clear();
            for (int i = 0; i < xfDataBeans.size(); i++) {
                PreXFDataBean preXFDataBean = xfDataBeans.get(i);
                if (itemId == preXFDataBean.getCid()) {
                    tempPreXFDataBean.add(preXFDataBean);
                }
            }

            consumeCategoryName.setText(itemName);
            consumeItemNum.setText("（" + tempPreXFDataBean.size() + "）");

            if (tempPreXFDataBean.size() == 0) {
                noConsumeItem.setVisibility(View.VISIBLE);
                if (xfListAdapter != null) {
                    xfListAdapter.notifyDataSetChanged();
                }
            } else {
                noConsumeItem.setVisibility(View.GONE);
                xfListAdapter = new PpXFListAdapter(PPXFActivity.this, tempPreXFDataBean);
                consumeItemGridview.setAdapter(xfListAdapter);
                consumeItemGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        PpXFDetailsDialog ppXFDetailsDialog = new PpXFDetailsDialog(PPXFActivity.this,
                                R.style.introDialog);
                        ppXFDetailsDialog.setPreXFDataBean(tempPreXFDataBean.get(position));
                        ppXFDetailsDialog.setPpXFPluginBean(ppXFPluginBean);
                        ppXFDetailsDialog.setMachineBean(machineBean);
                        ppXFDetailsDialog.setCanceledOnTouchOutside(false);
                        ppXFDetailsDialog.show();
                    }
                });
                consumeItemGridview.setOnScrollListener(new AbsListView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(AbsListView view, int scrollState) {

                    }

                    @Override
                    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                        if ((firstVisibleItem == 0 && visibleItemCount == totalItemCount) ||
                                firstVisibleItem > 0 && firstVisibleItem + visibleItemCount == totalItemCount) {
                            consumeItemDownMore.setVisibility(View.GONE);
                        } else {
                            consumeItemDownMore.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }
    }

    private class MyHandler extends Handler {
        private WeakReference<PPXFActivity> wrActivity;

        public MyHandler(PPXFActivity ppxfActivity) {
            wrActivity = new WeakReference<PPXFActivity>(ppxfActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            PPXFActivity mActivity = wrActivity.get();
            if (mActivity != null) {
                switch (msg.what) {
                    case 1:
                        ProcessWaitingUtil.closeProcessDialog();
                        String resultString = msg.obj.toString();
                        Log.i(TAG, "接口返回：" + resultString);
                        if (msg.arg1 == CONSUME_CATEGORY) {
                            PreItemReturnBean itemReturnBean = GsonUtils.parseSimpleJson(resultString,
                                    PreItemReturnBean.class);
                            if (itemReturnBean.getCode() == 200) {
                                itemBeans = gson.fromJson(itemReturnBean.getData(),
                                        new TypeToken<List<PreItemBean>>() {
                                        }.getType());
                                if (itemBeans != null) {
                                    setConsumeCategoryAdapter();
                                }
                            }
                        } else if (msg.arg1 == CONSUME_DATA) {
                            PreXFDataReturnBean xfDataReturnBean = GsonUtils.parseSimpleJson(resultString,
                                    PreXFDataReturnBean.class);
                            if (xfDataReturnBean.getCode() == 200) {
                                xfDataBeans = gson.fromJson(xfDataReturnBean.getData(),
                                        new TypeToken<List<PreXFDataBean>>() {
                                        }.getType());
                                setConsumeList();
                            }
                        }
                        break;

                    case 2:
                        ProcessWaitingUtil.closeProcessDialog();
                        if (msg.arg2 == CONSUME_CATEGORY) {
                            CommentCustomToast.makeText(PPXFActivity.this, "ip或port插件配置出错！", Toast.LENGTH_SHORT, false).show();
                        } else {
                            CommentCustomToast.makeText(PPXFActivity.this, getResources().getString(R.string.connect_err),
                                    Toast.LENGTH_SHORT, false).show();
                        }
                        break;
                }
            }
        }
    }

    ;

}
